package com.ynqxg.router.manager

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.widget.Toast

class RouterManager(private val context: Context) {

    companion object {
        private val activityRouterMap = mutableMapOf<String, Class<out Activity>>()

        fun putRouter(name: String, clazz: Class<out Activity>) {
            activityRouterMap[name] = clazz
        }

        fun init(vararg modules: String) {
            modules.forEach {
                try {
                    Class.forName("router.register.${it}.RegisterRouter").newInstance()
                } catch (e: Exception) {
                    throw NotRegisterModuleException()
                }
            }
        }
    }

    fun routerTo(name: String, extras: Intent? = null) {
        val activityClass = activityRouterMap[name]
        if (activityClass != null) {
            val intent = Intent(context, activityClass)
            if (extras != null) {
                intent.putExtras(extras)
            }
            context.startActivity(intent)
        } else {
            Toast.makeText(context, "该Router未注册", Toast.LENGTH_SHORT).show()
        }
    }

    fun getClass(name: String): Class<out Activity>? {
        return activityRouterMap[name]
    }

    class NotRegisterModuleException : Exception(
        "模块名称错误或未在gradle文件中的ksp模块再注册，如:\n" +
                "   android {\n" +
                "      ...\n" +
                "      ksp {\n" +
                "         arg(\"module\", \"app\")\n" +
                "      }\n" +
                "   }\n"
    )

}